#include "Mystd.h"

_FILE* _fopen(const char* filename,const char* mode)
{
	// 检查文件打开方式 + 调用open
	// mode == "w"/"r"/"a"
	int fd = -1;
	if(strcmp(mode,"w") == 0)// 只写
	{
		fd = open(filename,O_WRONLY|O_CREAT|O_TRUNC,PERN);
	}
	else if(strcmp(mode,"r") == 0)// 只读
	{
		fd = open(filename,O_RDONLY,PERN);
		
	}
	else if(strcmp(mode,"a") == 0)// 追加
	{
		fd = open(filename,O_WRONLY|O_CREAT|O_APPEND,PERN);
	}
	else
	{
		return NULL;
	}
	
	if(fd == -1)return NULL;

	// 构造_FILE结构体对象
	_FILE* pf = (_FILE*)malloc(sizeof(_FILE));
	if(pf == NULL)return NULL;

	pf->fileno = fd;
	pf->flag = FLUSH_NONE;// 缓冲策略默认全缓冲
	if(pf->fileno == 1 || pf->fileno == 2)pf->flag = FLUSH_LINK;
	pf->out_pos = 0;
	memset(pf->outbuff,'0',sizeof(pf->outbuff));
	
	return pf;
}


int _fwrite(const char* buff,int len,_FILE* stream)
{
	// 数据导入到缓冲区
	memcpy(&stream->outbuff[stream->out_pos],buff,len);
	stream->out_pos += len;

	if(stream->flag&FLUSH_ALL)// 全缓冲
	{
		if(stream->out_pos >= SIZE)
		{
			write(stream->fileno,stream->outbuff,stream->out_pos);
			stream->out_pos = 0;
		}
	}
	else if(stream->flag&FLUSH_LINK)// 行缓冲
	{
		if(stream->outbuff[stream->out_pos-1] == '\n')
		{
			write(stream->fileno,stream->outbuff,stream->out_pos);
			stream->out_pos = 0;
		}
	}
	else// 无缓冲
	{
		write(stream->fileno,stream->outbuff,stream->out_pos);
		stream->out_pos = 0;
	}

	return len;
}

void _fflush(_FILE* stream)
{
	if(stream->out_pos == 0)return;
	write(stream->fileno,stream->outbuff,stream->out_pos);
	stream->out_pos = 0;
}

void _fclose(_FILE* stream)
{
	_fflush(stream);// 文件关闭前刷新缓冲区
	close(stream->fileno);// 调用close
	free(stream);// 释放FILE对象
}



















